/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:itsm-gateway
 * Create Time: 2016年3月28日 下午7:04:40
 */
package com.lenovo.lmrp.server.itsmgateway.spi;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.jboss.resteasy.plugins.guice.RequestScoped;

import com.lenovo.lmrp.api.itsmgateway.IItsmProject;
import com.lenovo.lmrp.api.model.RestResponse;
import com.lenovo.lmrp.api.model.entity.EngineerPO;
import com.lenovo.lmrp.api.model.entity.ProjectExtensePO;
import com.lenovo.lmrp.api.model.entity.ProjectPO;
import com.lenovo.lmrp.api.model.entity.TicketPO;
import com.lenovo.lmrp.api.model.view.ClientVO;
import com.lenovo.lmrp.api.model.view.EngineerVO;
import com.lenovo.lmrp.api.model.view.ProjectVO;
import com.lenovo.lmrp.api.model.view.ServiceProviderVO;
import com.lenovo.sdc.framework.annotation.RestService;
import com.lenovo.sdc.framework.dao.ADaoFactory;
import com.lenovo.sdc.framework.dao.ICommonDAO;
import com.lenovo.sdc.framework.dao.ICommonDAO.FinderEnum;
import com.lenovo.sdc.framework.dao.RecordFilter;
import com.lenovo.sdc.framework.util.CommonUtil;
import com.lenovo.sdc.framework.util.Condition;
import com.lenovo.sdc.framework.util.Condition.OperatorEnum;
import com.lenovo.sdc.framework.util.Condition.RelationEnum;
import com.lenovo.sdc.framework.util.PageData;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * 
 * @author zx-lxj
 * @version v1.0
 */
@RestService
@Path("/itsm/v1")
@Consumes("application/json;charset-utf-8")
@Produces("application/json;charset-utf-8")
@RequestScoped
public class ItsmProjectlmpl implements IItsmProject {

    /**
     * return project base inforation and its extension data
     * 
     * @see com.lenovo.lmrp.api.itsmgateway.IItsmProject#getProject(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public RestResponse<ProjectPO> getProject(String itsmCode, String projectid) {
        try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
            ProjectPO project = dao.get(ProjectPO.class, projectid);
            project.setOthers(dao.get(ProjectExtensePO.class, projectid));
            return new RestResponse<ProjectPO>(project);
        }
        catch (Exception exp) {
            TraceableException.writeLog(ErrorCode.DB_QUERY_FAILED, "query project", exp);
            return new RestResponse<ProjectPO>(ErrorCode.COMM_ERROR.getCode(), exp.getMessage(), null);
        }
    }
    
    /**
     * return project 
     * @see com.lenovo.lmrp.api.itsmgateway.IItsmProject#getProjectByTicketId(java.lang.String, java.lang.String)
     */
    @Override
    public RestResponse<ProjectPO> getProjectByTicketId(String itsmCode,String ticketid){
        try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
            TicketPO ticketPO = dao.get(TicketPO.class, ticketid);
            if (Objects.nonNull(ticketPO)) {
            	ProjectPO project = dao.get(ProjectPO.class, ticketPO.getProjectId());
                return new RestResponse<ProjectPO>(project);
            }
            else {
            	return new RestResponse<ProjectPO>(1, "error", null);
            }
        }
        catch (Exception exp) {
            TraceableException.writeLog(ErrorCode.DB_QUERY_FAILED, "query project", exp);
            return new RestResponse<ProjectPO>(ErrorCode.COMM_ERROR.getCode(), exp.getMessage(), null);
        }
    }

    /**
     * @see com.lenovo.lmrp.api.itsmgateway.IItsmProject#listProject(java.lang.String,
     *      java.lang.String, java.lang.String)
     */
    @Override
    public RestResponse<PageData<ProjectPO>> listProject(String itsmCode, String id, String name, String status,
                                                       int page, int rows) {
        try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
            RecordFilter filter = new RecordFilter();
            if (CommonUtil.nonNullAndEmpty(id)) {
                filter.addCondition(new Condition<String, Object>("id", id, OperatorEnum.LIKE));
            }
            if (CommonUtil.nonNullAndEmpty(name)) {
                filter.addCondition(new Condition<String, Object>("name", name, OperatorEnum.LIKE), RelationEnum.AND);
            }
            if (CommonUtil.nonNullAndEmpty(status)) {
                String[] split = status.split(",");
                Object[] statuss = new Object[split.length];
                for (int i = 0; i < statuss.length; i++) {
                    statuss[i] = Integer.parseInt(split[i]);
                }
                filter.addCondition(new Condition<String, Object>("status", statuss, OperatorEnum.IN), RelationEnum.AND);
            }

            PageData<ProjectPO> pageData = null;
            pageData = new PageData<>(page, rows, true);
            dao.filteByCondition(ProjectPO.class, filter, pageData);
            
            return new RestResponse<PageData<ProjectPO>>(0, "OK", pageData);
        }
        catch (Exception exp) {
            TraceableException.writeLog(ErrorCode.DB_QUERY_FAILED, "query project", exp);
            return new RestResponse<PageData<ProjectPO>>(ErrorCode.COMM_ERROR.getCode(), exp.getMessage(), null);
        }
    }

    @Override
    public RestResponse<List<EngineerVO>> listProjectEngineer(String itsmCode, String projectID, String groupID,
                                                              String provinces, String citys) {
        try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
            RecordFilter filter = new RecordFilter();
            filter.addCondition(new Condition<String, Object>("pe.projectid", projectID));
            if (CommonUtil.nonNullAndEmpty(groupID))
                filter.addCondition(new Condition<String, Object>("pe.groupid", Integer.parseInt(groupID)));
            if (CommonUtil.nonNullAndEmpty(provinces))
                filter.addCondition(new Condition<String, Object>("e.province", provinces.split("[\\,]"),
                    OperatorEnum.IN));
            if (CommonUtil.nonNullAndEmpty(citys))
                filter.addCondition(new Condition<String, Object>("e.city", citys.split("[\\,]"), OperatorEnum.IN));

            List<EngineerPO> poList = dao.getRegisteredFinder(FinderEnum.SQL).findByNamedQuery(
                "udq_findprojectengineer", filter);
            List<EngineerVO> voList = new ArrayList<>(poList.size());
            poList.forEach(po -> {
                EngineerVO vo = new EngineerVO();
                vo.setEngineerid(po.getId());
                vo.setName(po.getFullName());
                vo.setLoginname(po.getLoginName());
                vo.setProvinceName(po.getProvince());
                vo.setCityName(po.getCity());
                vo.setPhone(po.getPhone());
                vo.setStatus(po.getStatus().ordinal());
                voList.add(vo);
            });
            return new RestResponse<List<EngineerVO>>(0, "OK", voList);
        }
        catch (Exception exp) {
            exp.printStackTrace();
            return new RestResponse<List<EngineerVO>>(ErrorCode.COMM_ERROR.getCode(), exp.getMessage(), null);
        }
    }

    @Override
    public RestResponse<List<ProjectVO>> listEngineerProject(String itsmCode, String engineerID, String groupID,
                                                             String provinces, String citys) {
        try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
            String sql = "select distinct(t.id),t.name,t.description,t.status,t.checkattachment,t.begintime,t.endtime "
                            + "from ITSM_PROJECT t, ITSM_PROJECT_ENGINEER t1 "
                            + "where t.id = t1.projectid and t1.engineerid=?";
            String[] engineerIDs = new String[] { engineerID };
            List<ProjectPO> pos = dao.getRegisteredFinder(FinderEnum.SQL).findMappedRecord(sql, ProjectPO.class,
                engineerIDs);
            List<ProjectVO> vos = new ArrayList<>(pos.size());
            for (ProjectPO po : pos) {
                ProjectVO vo = new ProjectVO();
                vo.setProjectId(po.getId());
                vo.setProjectName(po.getName());
                vos.add(vo);
            }
            return new RestResponse<List<ProjectVO>>(0, "OK", vos);
        }
        catch (Exception exp) {
            exp.printStackTrace();
            return new RestResponse<List<ProjectVO>>(ErrorCode.COMM_ERROR.getCode(), exp.getMessage(), null);
        }
    }

    /**
     * @see com.lenovo.lmrp.api.itsmgateway.IItsmProject#getServiceProvider(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public RestResponse<ServiceProviderVO> getServiceProvider(String itsmCode, String spid) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see com.lenovo.lmrp.api.itsmgateway.IItsmProject#getClient(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public RestResponse<ClientVO> getClient(String itsmCode, String clientid) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 
     * @see com.lenovo.lmrp.api.itsmgateway.IItsmProject#updateProjectExtProps(java.lang.String, com.lenovo.lmrp.api.model.entity.ProjectExtensePO)
     */
    @Override
    public RestResponse<ProjectExtensePO> updateProjectExtProps(String itsmCode,ProjectExtensePO projectExtensePO) {
        // TODO Auto-generated method stub
        try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
            dao.beginTrans();
            dao.saveOrUpdate(projectExtensePO);
            dao.endTrans();
            return new RestResponse<ProjectExtensePO>(0, "OK", null);
        }
        catch (Exception exp) {
            //throw new TraceableException(ErrorCode.DB_UPDATE_FAILED, exp);
            return new RestResponse<ProjectExtensePO>(ErrorCode.DB_UPDATE_FAILED.getCode(), exp.getMessage(), null);
        }
    }


}
